package com.macro.mall.portal.service.impl;

import com.macro.mall.portal.domain.ConfirmOrderResults;
import com.macro.mall.portal.domain.OmsOrder;
import com.macro.mall.portal.domain.Product;
import com.macro.mall.portal.domain.SeckillEvent;
import com.macro.mall.portal.service.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author：尚志豪
 * @Package：com.macro.mall.portal.service.impl
 * @Project：mall-swarm-B
 * @name：SeckillService
 * @Date：2024/11/1 16:12
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private SeckillEventRepository seckillEventRepository;
    @Autowired
    private OrderService orderService;


    @Override
    public void modifyStock(Long productId, int quantity) {
        validateSeckill(productId,quantity);
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));
        if (product.getStock() < quantity) {
            throw new RuntimeException("库存不足");
        }
    }

    @Override
    public ConfirmOrderResults seckill(Long productId, Long userId) {
        RLock lock = redissonClient.getLock("seckillLock:" + productId);
        ConfirmOrderResults result;

        try {
            if (lock.tryLock(10,5, TimeUnit.SECONDS)) {
                if (!productService.checkStock(productId)) {
                    return new ConfirmOrderResults(false,"库存不足");
                }

                productService.deductStock(productId);

                result = generateOrder(productId, userId);
            }else {
                return new ConfirmOrderResults(false,"请稍后再试");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new ConfirmOrderResults(false, "系统异常");
        }finally {
            if (lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
        return result;
    }

    private ConfirmOrderResults generateOrder(Long productId, Long userId) {

        OmsOrder order = new OmsOrder();
        order.setProductId(productId);
        order.setUserId(userId);
        order.setOrderStatus("已支付");
        order.setCreateTime(new Date());

        try {
            orderService.saveOrder(order);
        } catch (Exception e) {
            // 处理异常，例如保存失败
            return new ConfirmOrderResults(false, "订单生成失败：" + e.getMessage());
        }
        return new ConfirmOrderResults(true, "订单成功，订单ID: " + order.getId());
    }

    private void validateSeckill(Long productId, int quantity) {
        if (!checkStock(productId,quantity)){
            throw new RuntimeException("库存不足");
        }
        if (!checkTime(productId)){
            throw new RuntimeException("不在秒杀时间内");
        }
        if (!checkStatus(productId)) {
            throw new RuntimeException("活动已结束");
        }
    }

    private boolean checkStock(Long productId,int quantity) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));
        return product.getStock() >= quantity;
    }

    private boolean checkTime(Long productId) {
        SeckillEvent event = seckillEventRepository.findActiveEventByProductId(productId);
        if (event == null) {
            return false;
        }
        LocalDateTime now = LocalDateTime.now();
        return now.isAfter(event.getStartTime()) && now.isBefore(event.getEndTime());
    }

    private boolean checkStatus(Long productId) {
        SeckillEvent event = seckillEventRepository.findActiveEventByProductId(productId);
        return event != null && event.isActive();
    }


}
